import { calculateMA } from './dealKline.js';
import {
  bxzt_day,
  yl_day,
  gf_day,
  xny_day,
  xnyc_day,
  xp_day,
  mt_day,
  bj_day,
  fdc_day,
  zhuru_day
} from "./../../lib/api/section.js";

// 股票api传回来的数据  的总数
let stock_all_num=800
// 根据股票代码获取前缀
const getSecidPrefix = (code) => {
  return /^(002|300|000|159)/.test(code) ? 0 : 1;
};

// URL 生成函数集合
const urlGenerators = {
  urlDeal12: (url) => `https://datacenter-web.eastmoney.com/api/data/v1/get?reportName=RPT_DMSK_TS_STOCKEVALUATE&filter=(SECURITY_CODE="${url}")&columns=ALL&source=WEB&client=WEB&sortColumns=TRADE_DATE&sortTypes=-1`,
  urlDeal11: (url) => `https://www.iwencai.com/diag/block-detail?pid=11665&codes=${url}&codeType=stock&info={"view":{"nolazy":1,"parseArr":{"_v":"new","dateRange":[],"staying":[],"queryCompare":[],"comparesOfIndex":[]},"asyncParams":{"tid":137}}}`,
  urlDeal9: (url) => `https://data.eastmoney.com/stockcomment/api/${url}.json`,
  urlDeal8: () => "https://datacenter-web.eastmoney.com/api/data/v1/get?filter=(SECURITY_CODE%3D%22601318%22)&columns=ALL&source=WEB&client=WEB&reportName=RPT_CUSTOM_STOCK_PK",
  urlDeal7: (url) => `https://push2.eastmoney.com/api/qt/stock/fflow/kline/get?lmt=0&klt=1&fields1=f1,f2,f3,f7&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61,f62,f63,f64,f65&secid=${getSecidPrefix(url)}.${url}`,
  urlDeal6: (url, num2, type) => {
    const num1 = getSecidPrefix(url);
    const defaultUrl = `https://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get?lmt=0&klt=${num2}&fields1=f1,f2,f3,f7&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61,f62,f63,f64,f65&secid=${num1}.${url}`;
    return type ? `https://push2.eastmoney.com/api/qt/ulist.np/get?fltt=2&secids=${num1}.${url}&fields=f61,f62,f184,f66,f69,f72,f75,f78,f81,f84,f87,f64,f65,f70,f71,f76,f77,f82,f83,f164,f166,f168,f170,f172,f252,f253,f254,f255,f256,f124,f6,f278,f279,f280,f281,f282` : defaultUrl;
  },
  urlDeal5: (url) => `https://www.iwencai.com/diag/block-detail?pid=8093&codes=${url}&codeType=stock&info={"view":{"nolazy":1,"parseArr":{"_v":"new","dateRange":[],"staying":[],"queryCompare":[],"comparesOfIndex":[]},"asyncParams":{"tid":137}}}`,
  urlDeal4: (url) => `https://data.eastmoney.com/stockcomment/stock/${url}.html#zlkp`,
  urlDeal3: (url) => `https://www.iwencai.com/stockpick/search?typed=1&preParams=&ts=1&f=1&qs=index_rewrite&selfsectsn=&querytype=stock&searchfilter=&tid=stockpick&w=${url}`,
  urlDeal2: (url) => `https://www.iwencai.com/diag/block-detail?pid=10331&codes=${url}&codeType=stock&info={"view":{"nolazy":1,"parseArr":{"_v":"new","dateRange":[],"staying":[],"queryCompare":[],"comparesOfIndex":[]},"asyncParams":{"tid":137}}}`,
  urlDeal: (url, type) => {
    const num1 = getSecidPrefix(url);
    const num3 = type === 1 ? stock_all_num : 145;
    return `https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=${num1}.${url}&fields1=f1,f2,f3,f4,f5&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61&lmt=${num3}&klt=10${type}&fqt=1&end=30000101`;
  },
  urlDeal10: () => "https://push2his.eastmoney.com/api/qt/stock/kline/get?secid=1.000001&fields1=f1,f2,f3,f4,f5&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61&lmt=100&klt=101&fqt=1&end=30000101"
};

// 导出 URL 生成函数
export const {
  urlDeal12,
  urlDeal11,
  urlDeal9,
  urlDeal8,
  urlDeal7,
  urlDeal6,
  urlDeal5,
  urlDeal4,
  urlDeal3,
  urlDeal2,
  urlDeal,
  urlDeal10
} = urlGenerators;

// 股票代码转基金代码映射
const fundCodeMap = {
  '600519': bj_day,
  '603259': yl_day,
  '601318': bxzt_day,
  '601012': gf_day,
  '601898': mt_day,
  '002371': xp_day,
  '300274': xnyc_day,
  '300750': xny_day,
  '600048': fdc_day,
  '300498': zhuru_day
};

// 联系转化为了基金代码
export const dealFundCode = (code) => fundCodeMap[code] || null;

// 根据类型切换 URL 生成函数
export const switchUrlDeal = (type, url, type1) => {
  if (!url) return "";
  const generatorMap = {
    1: () => urlDeal(url, type1),
    2: () => urlDeal2(url),
    3: () => urlDeal3(url),
    4: () => urlDeal4(url),
    5: () => urlDeal5(url),
    6: () => urlDeal6(url, type1),
    7: () => urlDeal7(url),
    8: () => urlDeal8(),
    9: () => urlDeal9(url),
    10: () => urlDeal10()
  };
  return generatorMap[type] ? generatorMap[type]() : "";
};

// 按钮数组
export const btn_array2 = [
  { name: "中国平安", tip: "保险主题", num: "601318" },
  { name: "隆基绿能", tip: "光伏", num: "601012" },
  { name: "中煤能源", tip: "煤炭", num: "601898" },
  { name: "贵州茅台", tip: "白酒", num: "600519" },
  { name: "药明康德", tip: "医疗", num: "603259" },
  { name: "北方华创", tip: "芯片", num: "002371" },
  { name: "阳光电源", tip: "新能源", num: "300274" },
  { name: "宁德时代", tip: "电池", num: "300750" },
  { name: "保利发展", tip: "房地产", num: "600048" },
  { name: "温氏股份", tip: "猪肉", num: "300498" }
];

// 日期格式化函数
const dateFormat = (fmt, date) => {
  const opt = {
    "Y+": date.getFullYear().toString(),
    "m+": (date.getMonth() + 1).toString(),
    "d+": date.getDate().toString(),
    "H+": date.getHours().toString(),
    "M+": date.getMinutes().toString(),
    "S+": date.getSeconds().toString()
  };
  for (let k in opt) {
    const ret = new RegExp(`(${k})`).exec(fmt);
    if (ret) {
      fmt = fmt.replace(
        ret[1],
        ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
      );
    }
  }
  return fmt;
};

// 设置截取的数字
export var num2 = 362;

// 处理数据
export const dealData = (data2, type, name, num, type2, num3) => {
  let array2 = [];
  let time1 = [];
  let num1 = [];
  num2 = data2.length + 1;


  data2.forEach((element2, index2) => {
    switch (type) {
      case 1:
        array2.push(parseFloat(element2[6].toFixed(2)));
        time1.push(dateFormat("YYYY-mm-dd", new Date(element2[9] * 1000)));
        num1.push(parseFloat(element2[1]));
        break;
      case 2:
        array2.push(parseFloat(element2.split(",")[8]));
        time1.push(element2.split(",")[0]);
        num1.push(num === 6 ? parseFloat((parseInt(element2.split(",")[num]) / 100000000).toFixed(2)) : parseFloat(element2.split(",")[num]));
        break;
      case 3:
        array2.push(index2 + 1);
        time1.push(dateFormat("YYYY-mm-dd", new Date(element2[9] * 1000)));
        num1.push(parseFloat(element2[1]));
        break;
      case 4:
        num1.push(parseFloat((parseInt(element2.split(",")[num]) / 100000000).toFixed(2)));
        break;
      case 5:
        num1.push(parseFloat(element2.split(",")[num]));
        break;
    }
  });

  return {
    name,
    num: num1,
    time: time1,
    array: array2,
    type_echarts: type2 === undefined ? undefined : 'bar',
    itemStyle: num3 === undefined ? undefined : 2
  };
};

// 计算止损位
export const calculateStopLoss2 = (array_all, data1, data2, input_name6, time1) => {
  const ma5 = calculateMA(5, array_all[0].klines);
  const ma10 = calculateMA(10, array_all[0].klines);
  const ma20 = calculateMA(20, array_all[0].klines);
  const ma30 = calculateMA(30, array_all[0].klines);
  const ma60 = calculateMA(60, array_all[0].klines);
  const max_data_num = dealData(data1, 2, "最高值", 3).num;
  const min_data_num = dealData(data1, 2, "最低值", 4).num;
  const this_data_num = dealData(data1, 2, "当前值", 2).num;
  const this_data = time1;
  const end_time = input_name6 === "" ? this_data[this_data.length - 1] : input_name6;
  const start_time = this_data[this_data.indexOf(end_time) - 20];
  const startIndex = this_data.indexOf(start_time) + 1;
  const endIndex = this_data.indexOf(end_time) + 1;
  const max_data_array = dealReduce(max_data_num, startIndex, endIndex);
  const min_data_array = dealReduce(min_data_num, startIndex, endIndex);
  const this_data_array = dealReduce(this_data_num, startIndex, endIndex);
  const deal_data2 = dealDateData(max_data_num, min_data_num, this_data_num, startIndex, endIndex, this_data.length);
  return {
    this_data,
    max_data_array,
    min_data_array,
    this_data_array,
    ma5,
    ma10,
    ma20,
    ma30,
    ma60,
    this_data_num,
    max_data_num,
    min_data_num,
    array_data: [
      ma5[ma5.length - 1],
      ma10[ma10.length - 1],
      ma20[ma20.length - 1],
      ma30[ma30.length - 1],
      ma60[ma60.length - 1],
      this_data_num[this_data_num.length - 1]
    ],
    array_end: data1,
    deal_data2
  };
};

// 处理数据缩减
const dealReduce = (max_data_num, start_time, end_time) => {
  const max_data_array = max_data_num.slice(start_time + 1, end_time + 1);
  const reduce_max_datat = max_data_array.reduce((acc, val) => acc + parseFloat(val), 0);
  return (reduce_max_datat / max_data_array.length).toFixed(2);
};

// 处理数组重复填充
const moreArray = (data) => Array(20).fill(data);

// 处理日期数据
const dealDateData = (max_data_num, min_data_num, this_data_num, start_time, end_time, length1) => {
  const array1 = [];
  const array2 = [];
  const array3 = [];
  const zsw_array = [];
  const zcw_array = [];
  const max_num1 = [];
  const min_num1 = [];
  const zcw3 = [];
  for (let i = 0; i < length1 - 20; i++) {
    const currentEndTime = end_time - i;
    const currentStartTime = start_time - i;
    const maxDataArray = dealReduce(max_data_num, currentStartTime, currentEndTime);
    const minDataArray = dealReduce(min_data_num, currentStartTime, currentEndTime);
    const thisDataArray = dealReduce(this_data_num, currentStartTime, currentEndTime);
    array1.push(maxDataArray);
    array2.push(minDataArray);
    array3.push(thisDataArray);
    zsw_array.push(parseFloat(maxDataArray * 0.95).toFixed(2));
    zcw_array.push(parseFloat((maxDataArray - minDataArray) * 0.618 + parseFloat(minDataArray)).toFixed(2));
    const maxSlice = max_data_num.slice(currentEndTime - 20, currentEndTime);
    const minSlice = min_data_num.slice(currentEndTime - 20, currentEndTime);
    let maxItem1 = Math.max(...maxSlice);
    maxItem1 = maxItem1 === -Infinity ? parseFloat(max_num1.slice(-1)[0]) : maxItem1;
    let minItem1 = Math.min(...minSlice);
    minItem1 = minItem1 === Infinity ? parseFloat(min_num1.slice(-1)[0]) : minItem1;
    max_num1.push(maxItem1);
    min_num1.push(minItem1);
    zcw3.push((maxItem1 - minItem1) * 0.618 + minItem1);
  }
  return {
    max_array: array1.concat(moreArray(array1[array1.length - 1])),
    min_array: array2.concat(moreArray(array2[array2.length - 1])),
    this_array: array3.concat(moreArray(array3[array3.length - 1])),
    zcw3: zcw3.concat(moreArray(zcw3[zcw3.length - 1])),
    zsw_array: zsw_array.concat(moreArray(zsw_array[zsw_array.length - 1])),
    zcw_array: zcw_array.concat(moreArray(zcw_array[zcw_array.length - 1])),
    max_num1: max_num1.concat(moreArray(max_num1[max_num1.length - 1])),
    min_num1: min_num1.concat(moreArray(min_num1[min_num1.length - 1]))
  };
};